/**
 * Created by Administrator on 2021/4/23 0023.
 */
import axios from "axios";

const Axios = axios.create({
    baseURL: "",
    responseType: "json",
    withCredentials: true, // 是否允许带cookie这些
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
//timeout: 10000,

//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
    config => {
        // 在发送请求之前做某件事
        if (
            config.method === "post"
        ) {
            // 序列化
            config.data = config.data;
        }

        // 若是有做鉴权token , 就给头部带上token
        // 若是需要跨站点,存放到 cookie 会好一点,限制也没那么多,有些浏览环境限制了 localstorage 的使用
        // 这里localStorage一般是请求成功后我们自行写入到本地的,因为你放在vuex刷新就没了
        // 一些必要的数据写入本地,优先从本地读取
        if (localStorage.token) {
            config.headers.Authorization = localStorage.token;
        }
        return config;
    },
    error => {
        let st = '';
        error.response && error.response.status ? st = error.response.status : st = JSON.stringify(error);
        throwErrorTips('请求超时，请检查网络',st)

        return Promise.reject(error);
    }
);

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
    res => {
        //对响应数据做些事
        if (res.data && !res.data.success) {
            throwErrorTips('',res.data.msg)
            return Promise.reject(res.data);
        }
        return res.data;
    },
    error => {
        return Promise.reject(error);
    }
);

export default function(url, data = {}, method='GET', opt){
    return new Promise((resolve,reject)=>{
        Axios({
            url: url,
            params: method == 'GET' ? data : null,
            data: method == 'POST' ? data : null,
            method: method,
            opt
        })
        .then(res=>resolve(res))
        .catch(err=>reject(err))
    })
}
